package cn.wolfcode.car.business.service.impl;

import cn.wolfcode.car.business.domain.BpmnInfo;
import cn.wolfcode.car.business.domain.CarPackageAudit;
import cn.wolfcode.car.business.domain.ServiceItem;
import cn.wolfcode.car.business.mapper.BpmnInfoMapper;
import cn.wolfcode.car.business.mapper.CarPackageAuditMapper;
import cn.wolfcode.car.business.mapper.ServiceItemMapper;
import cn.wolfcode.car.business.qo.CarPackageAuditQueryObject;
import cn.wolfcode.car.business.service.ICarPackageAuditService;
import cn.wolfcode.car.common.base.page.TablePageInfo;
import cn.wolfcode.car.common.exception.BusinessException;
import cn.wolfcode.car.shiro.ShiroUtils;
import com.github.pagehelper.PageHelper;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.InputStream;
import java.util.*;

@Service
@Transactional
public class CarPackageAuditServiceImpl implements ICarPackageAuditService {

    @Autowired
    private CarPackageAuditMapper carPackageAuditMapper;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private BpmnInfoMapper bpmnInfoMapper;
    @Autowired
    private ServiceItemMapper serviceItemMapper;


    @Override
    public TablePageInfo<CarPackageAudit> query(CarPackageAuditQueryObject qo) {
        PageHelper.startPage(qo.getPageNum(), qo.getPageSize());
        return new TablePageInfo<CarPackageAudit>(carPackageAuditMapper.selectForList(qo));
    }

    @Override
    public CarPackageAudit get(Long id) {
        return carPackageAuditMapper.selectOne(id);
    }

    @Override
    public InputStream processImg(Long id) {
        // 获得流程实例明细对象
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectOne(id);
        // 获得流程定义明细对象
        BpmnInfo bpmnInfo = bpmnInfoMapper.selectOne(carPackageAudit.getBpmnInfoId());
        if (bpmnInfo == null) {
            throw new BusinessException("该流程已删除,请联系管理员!");
        }
        List<String> activeActivityIds = new ArrayList<>();
        InputStream inputStream = null;
        // 判断状态是否是审核中 如果是审核中要求高亮
        if (CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            activeActivityIds = runtimeService.getActiveActivityIds(carPackageAudit.getInstanceId());
        }else {
            activeActivityIds = Collections.EMPTY_LIST;
        }
        // 根据流程定义 id 获得流程定义模型对象
        DefaultProcessDiagramGenerator defaultProcessDiagramGenerator = new DefaultProcessDiagramGenerator();
        // 生成流程图
        BpmnModel bpmnModel = repositoryService.getBpmnModel(bpmnInfo.getActProcessId());
        inputStream = defaultProcessDiagramGenerator.generateDiagram(bpmnModel, activeActivityIds, Collections.EMPTY_LIST,
                "楷体", "楷体", "楷体");
        return inputStream;
    }

    @Override
    public void cancelApply(Long id) {
        // 获得carPackageAudit对象
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectOne(id);
        // 判断状态是否是审核中,如果不是无法撤销
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("无法撤销");
        }
        // 修改 carPackageAudit 对象状态为审核撤销
        carPackageAuditMapper.changeStatus(CarPackageAudit.STATUS_CANCEL,id);
        // 修改服务单例状态为初始化
        serviceItemMapper.changeStatus(ServiceItem.AUDITSTATUS_INIT,carPackageAudit.getServiceItemId());
        // 删除流程实例
        runtimeService.deleteProcessInstance(carPackageAudit.getInstanceId(),"撤销审批");
    }

    @Override
    public void audit(Long id, Integer auditStatus, String info) {
        // 获得 carPackageAudit 对象
        CarPackageAudit carPackageAudit = carPackageAuditMapper.selectOne(id);
        // 判断状态是否为审核中 不是则抛出异常
        if (!CarPackageAudit.STATUS_IN_ROGRESS.equals(carPackageAudit.getStatus())) {
            throw new BusinessException("异常操作");
        }
        // 获得任务节点对象
        Task currentTake = taskService.createTaskQuery().
                processInstanceId(carPackageAudit.getInstanceId()).
                singleResult();
        // 设置流程变量
        Map<String,Object> map = new HashMap<>();
        map.put("auditStatus",auditStatus);
        // 完成当前节点对象
        taskService.complete(currentTake.getId(),map);
        // 判断审批是否通过
        if (CarPackageAudit.STATUS_PASS.equals(auditStatus)) {
            // 审批通过
            // 通过后获得下一个任务节点
            Task nextTake = taskService.createTaskQuery().
                    processInstanceId(carPackageAudit.getInstanceId()).
                    singleResult();
            // 判断有没有下一个任务节点
            if (nextTake != null) {
                // 如果有,更新 carPackageAudit 的审核人 id
                carPackageAuditMapper.updateAuditorId(Long.valueOf(nextTake.getAssignee()),id);
                // 更新备注信息
                carPackageAudit.setInfo(carPackageAudit.getInfo() + "/" + ShiroUtils.getUser().getUserName() +"[通过:"+ info +"]");
            }else {
                // 如果没有,设置审核人为 null
                carPackageAuditMapper.updateAuditorId(null,id);
                // 跟新 carPackageAudit 审核状态为审核通过
                carPackageAuditMapper.changeStatus(CarPackageAudit.STATUS_PASS,id);
                // 更新 服务单项 审核状态为审核通过
                serviceItemMapper.changeStatus(ServiceItem.AUDITSTATUS_APPROVED,carPackageAudit.getServiceItemId());
                carPackageAudit.setInfo(carPackageAudit.getInfo() + "/" + ShiroUtils.getUser().getUserName() +"[通过:"+ info +"]");
            }
        }else {
            // 拒绝
            // 设置 carPackageAudit 审核状态为拒绝
            carPackageAuditMapper.changeStatus(CarPackageAudit.STATUS_REJECT,id);
            // 更新 服务单项 审核状态为 重新调整
            serviceItemMapper.changeStatus(ServiceItem.AUDITSTATUS_REPLY,carPackageAudit.getServiceItemId());
            // 更新备注信息
            carPackageAudit.setInfo(carPackageAudit.getInfo() + "/" + ShiroUtils.getUser().getUserName() +"[退回:"+ info +"]");
        }
        // 设置审核时间
        carPackageAudit.setAuditTime(new Date());
        // 更新 carPackageAudit 数据
        carPackageAuditMapper.update(carPackageAudit);
    }

}
